package com.cweb.admin.model.sys.sys_oss_record.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CopyObjectResult;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.cweb.admin.model.sys.sys_config.SysConfigConstant;
import com.cweb.admin.model.sys.sys_config.service.SysConfigService;
import com.cweb.framework.base.serivce.BaseSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.net.URL;
import java.util.Date;

/**
 * OSS上传工具
 */
@Service
public class ObjectStorageService extends BaseSerivce {
    @Autowired
    private SysConfigService sysConfigService;

    private OSS ossClient = null;

    private OSS getOSSClient() {
        if (null == ossClient) {
            ossClient = new OSSClientBuilder().build(
                    sysConfigService.getConfigStr(SysConfigConstant.PARAM_SYS_OSS_ALIYUN_ENDPOINT),
                    sysConfigService.getConfigStr(SysConfigConstant.PARAM_SYS_OSS_ALIYUN_ACCESS_KEY_ID),
                    sysConfigService.getConfigStr(SysConfigConstant.PARAM_SYS_OSS_ALIYUN_ACCESS_KEY_SECRET)
            );
        }
        return ossClient;
    }

    /**
     * 文件上传
     */
    public PutObjectResult upload(String bucketName, String key, InputStream input) {
        return upload(bucketName, key, input, new ObjectMetadata());
    }

    public PutObjectResult upload(String bucketName, String key, InputStream input, ObjectMetadata objectMetadata) {
        return getOSSClient().putObject(bucketName, key, input, objectMetadata);
    }

    /**
     * 取得连接url
     */
    public String getImgUrl(String bucketName, String key) {
        // 设置URL过期时间为10年 3600l* 1000*24*365*10
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        // 连接处理
        URL url = getOSSClient().generatePresignedUrl(bucketName, key, expiration);
        return url.toString();
    }

    /**
     * 地址复制
     */
    public CopyObjectResult copyFile(String sourceBucketName, String sourceObjectName, String destinationBucketName, String destinationObjectName) {
        // 连接处理
        return getOSSClient().copyObject(sourceBucketName, sourceObjectName, destinationBucketName, destinationObjectName);
    }

}
